﻿using Chaunce.FrameWork.NetCore.EasyRedis;
using Chaunce.FrameWork.NetCore.SysCore.Infrastructure;
using Chaunce.FrameWork.NetCore.Utility.Helpers;
using System;
using System.Collections.Generic;
using System.Text;

namespace Chaunce.Web.Core.Providers.Config
{
    /// <summary>
    /// 配置文件读取
    /// </summary>
    public class ConfigProvider : IConfigProvider
    {
        private readonly IChaunceFileProvider _fileProvider;
        private readonly ICacheManager _cacheManager;
        private readonly int cachetime = 60;

        public ConfigProvider(IChaunceFileProvider fileProvider,
            ICacheManager cacheManager)
        {
            _fileProvider = fileProvider;
            _cacheManager = cacheManager;
        }

        public Property GetProperty(string name)
        {
            string path = "~/config/" + name + ".config";

            return LoadConfig<Property>(path);
        }

        public void SetProperty(Property property, string name)
        {
            string path = "~/config/" + name + ".config";
            SaveConfig(property, path);
        }

        public bool IsXmlPropertyContains(Property property, string node, string strVal)
        {
            string properties = "," + property[node] + ",";
            return properties.Contains("," + strVal + ",");
        }

        //public UploadMap GetUploadConfig()
        //{
        //    string path = "~/config/uploads.config";
        //    return LoadConfig<UploadMap>(path);
        //}

        public string GetAdminGlobalConfig(string TagName)
        {
            string ConfigValue = string.Empty;
            try
            {
                Property siteConfig = this.GetProperty("global");
                ConfigValue = siteConfig[TagName];
            }
            catch
            {
                ConfigValue = string.Empty;
            }
            return ConfigValue;
        }

        private T LoadConfig<T>(string path)
        {
            object o = _cacheManager.Get<object>(path);

            if (o == null)
            {
                string real_path = _fileProvider.MapPath(path);
                o = XmlHelper.XmlDeserialize(real_path, typeof(T));
                //设置缓存
                _cacheManager.Set(path, o, cachetime);
            }
            return (T)o;
        }

        private void SaveConfig(object o, string path)
        {
            string real_path = _fileProvider.MapPath(path);
            XmlHelper.XmlSerializer(o, real_path);
            _cacheManager.Set(path, o, cachetime);
        }

        /// <summary>
        /// 获取appsetting.config配置文件值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string GetAppSettingValue(string key)
        {
            string path = "~/config/appsetting.config";
            var settings = LoadConfig<AppSetting>(path);
            return settings[key];
        }
    }
}
